package com.jason.bbs.article.service.impl;

import java.util.Date;

import javax.annotation.Resource;

import org.springframework.data.domain.Example;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.data.domain.Sort.Direction;
import org.springframework.stereotype.Service;

import com.jason.bbs.article.dao.ArticleDao;
import com.jason.bbs.article.service.ArticleService;
import com.jason.bbs.bean.article.Article;

@Service
public class ArticleServiceImpl implements ArticleService {
	@Resource
	private ArticleDao dao;

	@Override
	public Article add(Article article) {
		article.setStatus(1);
		article.setCreateTime(new Date());
		return dao.save(article);
	}

	@Override
	public void delete(String id) {
		if (exitis(id)) {
			Article article = dao.findById(Integer.valueOf(id)).get();
			article.setStatus(0);
			dao.save(article);
		}
	}

	@Override
	public Page<Article> find(Article article, int pageNumber, int pageSize) {
		Sort sort = new Sort(Direction.DESC, "id");
		Pageable page = new PageRequest(pageNumber, pageSize, sort);
		if (article == null) {
			return dao.findAll(page);
		} else {
			if (article.getStatus() == null) {
				article.setStatus(1);
			}
			return dao.findAll(Example.of(article), page);
		}
	}

	@Override
	public boolean exitis(String id) {
		Article article=new Article();
		article.setId(Integer.valueOf(id));
		return dao.exists(Example.of(article));
	}
}
